#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/08/03
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from datetime import datetime
from project.define import dev_logger
from project.modules import RecordParking, RecordEntrance, RecordExit, MemberUser


class Lane:
    def __init__(self, GateType) -> None:
        # 闸机信息
        self.GateID = ""
        self.GateType = GateType
        self.GateName = ""
        self.GateMethods = ""
        self.Position = ""
        self.GateAddr = ""
        self.GateGroup = ""
        self.Board = ""
        self.Version = ""
        # 闸机状态
        self.VehicleType = ""
        self.LicensePlate = ""
        self.LicensePlateImg = ""
        self.TicketNumber = ""
        self.CardNumber = ""
        self.GateTime = ""
        self.GateTemp = ""
        self.GateReady = True
        # 车场信息
        self.Name = ""
        self.Brand = ""
        self.Company = ""
        self.Address = ""
        self.Phone = ""
        self.Model = ""
        self.HourlyTimeout = ""
        # 通过消息
        self.GateMessage = ""
        # 车位类型
        self.ParkingType = ""
        self.Past = False
        # 入场信息
        self.ParkingID = None
        # 车位信息
        self.CarParkPlaces = []
        self.PlaceID = None
        self.PlaceProvide = 0
        self.PlaceParking = 0
        # 月租用户
        self.UserID = None

    def snapshot(self):
        """
        快照
        """
        return {
            "GateID":self.GateID,
            "GateName":self.GateName,
            "GateType":self.GateType,
            "VehicleType":self.VehicleType,
            "LicensePlate":self.LicensePlate,
            "LicensePlateImg":self.LicensePlateImg,
            "TicketNumber":self.TicketNumber,
            "CardNumber":self.CardNumber,
            "GateMessage":self.GateMessage,
            "ParkingType":self.ParkingType,
            "Past":self.Past,
            "GateTime":self.GateTime,
            "GateTemp":self.GateTemp,
            "PlaceID":self.PlaceID,
            "UserID":self.UserID
        }

    def refresh_carpark_setting(self, **kwargs):
        """
        更新车场信息
        """
        for k, v in kwargs.items():
            if hasattr(self, k):
                if getattr(self, k) != v:
                    setattr(self, k, v)

    def identify_carpark_place(self):
        """
        查找車位
        """
        for i in self.CarParkPlaces:
            if self.VehicleType == i['VehicleType']:
                if self.ParkingType == i['ParkingType']:
                    self.PlaceID = i['PlaceID']
                    self.PlaceProvide = i['Provide']
                    self.PlaceParking = i['Parking']
                    return i

    def __exit_event(self):
        """
        离场事件
        """
        p = RecordParking.query.filter_by(LicensePlate=self.LicensePlate,ExitTime=None,Deleted=False).first()
        if p:
            self.ParkingID = p.ParkingID
            if self.VehicleType == p.VehicleType:
                self.ParkingType = p.ParkingType
                place = self.identify_carpark_place()
                if place:
                    if self.ParkingType == "Monthly":
                        # 月租离场
                        self.UserID = p.UserID
                        m = MemberUser.query.filter_by(UserID=self.UserID).first()
                        if m:
                            if m.Enable:
                                if (m.ValidTime - datetime.now()).seconds > 0:
                                    if m.VehicleType == self.VehicleType:
                                        if self.TicketNumber == "":
                                            # 使用月租卡
                                            if 'Card' in place['ParkingMethods']:
                                                if self.CardNumber != "":
                                                    if self.CardNumber != m.CardNumber:
                                                        self.GateMessage = "卡號不符"
                                                        return 0
                                                else:
                                                    self.GateMessage = "等待拍卡"
                                                    return 0
                                            # 月租通过
                                            self.GateMessage = "月租離場"
                                            self.Past = True
                                        else:
                                            self.GateMessage = "請先拍卡"
                                    else:
                                        self.GateMessage = "車型不符"
                                else:
                                    self.GateMessage = "月租過期"
                            else:
                                self.GateMessage = "月租失效"
                        else:
                            self.GateMessage = "沒有月租"
                    elif self.ParkingType == "Hourly":
                         # 时租离场
                        if self.CardNumber == "":
                            if "Ticket" in place['ParkingMethods']:
                                if self.TicketNumber != "":
                                    if self.TicketNumber != p.TicketNumber:
                                        self.GateMessage = "票號不符"
                                        return 0
                                else:
                                    self.GateMessage = "等待驗票"
                                    return 0
                            if p.ChargeTime:
                                app_time = datetime.now()
                                if (app_time - p.ChargeTime).total_seconds() / 60 < self.HourlyTimeout:
                                    # 时租通过
                                    self.GateMessage = "時租離場"
                                    self.Past = True
                                else:
                                    self.GateMessage = "離場超時"
                            else:
                                self.GateMessage = "請先繳費"
                        else:
                            self.GateMessage = "拍卡無效"
                else:
                    self.GateMessage = "沒有車位"
            else:
                self.GateMessage = "車型不符"
        else:
            self.GateMessage = "沒有記錄"

    def __entrance_event(self):
        """
        入场事件
        """
        p = RecordParking.query.filter_by(LicensePlate=self.LicensePlate,ExitTime=None,Deleted=False).first()
        if not p:
            m = MemberUser.query.filter(MemberUser.LicensePlate.like(f"%{self.LicensePlate}%")).first()
            if m:
                # 月租入场
                self.ParkingType = m.ParkingType
                self.UserID = m.UserID
                p = RecordParking.query.filter_by(UserID=self.UserID,ExitTime=None,Deleted=False).first()
                if not p:
                    if m.Enable:
                        if (m.ValidTime - datetime.now()).seconds > 0:
                            if m.VehicleType == self.VehicleType:
                                # 车位处理
                                place = self.identify_carpark_place()
                                if place:
                                    if self.PlaceProvide > self.PlaceParking:
                                        if self.TicketNumber == "":
                                            # 使用月租卡
                                            if 'Card' in place['ParkingMethods']:
                                                if self.CardNumber != "":
                                                    if self.CardNumber != m.CardNumber:
                                                        self.GateMessage = "卡號不符"
                                                        return 0
                                                else:
                                                    self.GateMessage = "等待拍卡"
                                                    return 0
                                            # 月租通过
                                            self.GateMessage = "月租入場"
                                            self.Past = True
                                        else:
                                            self.GateMessage = "請先拍卡"
                                    else:
                                        self.GateMessage = "車位已滿"
                                else:
                                    self.GateMessage = "沒有車位"                        
                            else:
                                self.GateMessage = "車型不符"
                        else:
                            self.GateMessage = "月租過期"
                    else:
                        self.GateMessage = "月租失效"
                else:
                    self.GateMessage = "月租在場"
            else:
                # 时租入场
                self.ParkingType = "Hourly"
                place = self.identify_carpark_place()
                if place:
                    if self.PlaceProvide > self.PlaceParking:
                        if self.CardNumber == "":
                            # 使用时租票
                            if 'Ticket' in place['ParkingMethods']:
                                if self.TicketNumber == "":
                                    self.GateMessage = "等待取票"
                                    return 0
                            # 月租通过
                            self.GateMessage = "時租入場"
                            self.Past = True
                        else:
                            self.GateMessage = "請先取票"
                    else:
                        self.GateMessage = "車位已滿"
                else:
                    self.GateMessage = "沒有車位"        
        else:
            self.ParkingType = p.ParkingType
            self.GateMessage = "車已在場"

                    
    def __identify_lane_status(self):
        """
        分析车道状态
        """
        # 准备状态
        if self.GateReady:
            if self.LicensePlate not in ("", "UNKNOWN"):
                if self.VehicleType not in ("", "Barrier"):
                    if len(self.CarParkPlaces) > 0:
                        # 开始处理
                        if self.GateType == 'Entrance':
                            self.__entrance_event()
                        elif self.GateType == 'Exit':
                            self.__exit_event()
                    else:
                        self.GateMessage = "沒有車位"
                else:
                    if self.VehicleType == 'Barrier':
                        self.GateMessage = '閘機地感'
                    else:
                        self.GateMessage = "地感無效"
            else:
                if self.LicensePlate == 'UNKNOWN':
                    self.GateMessage = '車牌無效'
                else:
                    self.GateMessage = "沒有車牌"
        else:
            self.GateMessage = "尚未準備"

    def reset_status(self, **kwargs):
        """
        重置车道状态
        """
        self.Past = False
        self.UserID = None
        self.ParkingType = ""
        self.__dict__.update(**kwargs)
        dev_logger.debug(f"{self.GateType} => 车道状态重置")

    def lane_event(self, **kwargs):
        """
        事件处理
        """
        event = kwargs.copy()
        event.pop("CarParkPlaces")
        dev_logger.debug(f"{self.GateType} 车道事件 => {event}")
        self.reset_status(**kwargs)
        # 分析车辆出入情况
        self.__identify_lane_status()
        # 数据库处理
        snapshot = self.snapshot()
        if self.GateType == "Entrance":
            ret = RecordEntrance.insert_data(**snapshot)
            if self.Past:
                RecordParking.lane_entrance_record(**ret)
        elif self.GateType == "Exit":
            ret = RecordExit.insert_data(**snapshot)
            if self.Past:
                ret['ParkingID'] = self.ParkingID
                RecordParking.lane_exit_record(**ret)
        return snapshot